package kamikaze.service.product;

import java.io.PrintWriter;

import javax.persistence.EntityManager;

import kamikaze.ShoppingCart;
import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.UserSession;

import com.google.appengine.api.datastore.KeyFactory;

@ServiceConfig(path = "product/AddToShoppingCart.ajax", method = HttpMethod.POST)
public class ProductAddToShoppingCartService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		PrintWriter writer = ctx.getResponse().getWriter();

		if (ctx.getUserSession().getType() != UserSession.Type.User) {

			writer.print("you must login as user");
			return null;
		}

		Long id;

		try {
			id = Long.parseLong(ctx.getRequest().getParameter("id"));
		} catch (Exception e) {
			writer.print("invalid id " + e.getMessage());
			return null;
		}

		EntityManager em = ctx.getEntityManager();

		Product prod = em.find(Product.class, KeyFactory.createKey("Product", id));

		if (prod == null) {
			writer.print("no such product ");
			return null;
		}

		ShoppingCart.from(ctx).add(prod);

		writer.print("product " + prod.getName() + " added to your shopping cart");
		return null;
	}
}
